﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ADC.BL;
using ADC.DAL;
using ADC.Utilites;

namespace ADC.Web.Admin
{
    public partial class ListSlide : System.Web.UI.Page
    {
        log4net.ILog logger = log4net.LogManager.GetLogger("ListSlide");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                InintData();
            }
        }

        private void InintData()
        {
            try
            {
                var slides = SlideFactory.GetAll();
                foreach (var slide in slides)
                {
                    slide.ImagePath = "../" + slide.ImagePath;
                }
                GridViewSlide.DataSource = slides;
                GridViewSlide.DataBind();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                if (GlobalInfo.IsEnableDebugMode) throw;
            }

        }

        protected void GridViewSlide_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                var lblSlideID = (Label)GridViewSlide.Rows[e.NewEditIndex].FindControl("lblSlideID");
                if (lblSlideID != null && !string.IsNullOrEmpty(lblSlideID.Text))
                {
                    Response.Redirect("ManageSlide.aspx?Mode=1&ID=" + lblSlideID.Text, false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                if (GlobalInfo.IsEnableDebugMode) throw;
            }
        }

        protected void GridViewSlide_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                var lblSlideID = (Label)GridViewSlide.Rows[e.RowIndex].FindControl("lblSlideID");
                var lblImagePath = (Label)GridViewSlide.Rows[e.RowIndex].FindControl("lblImagePath");
                if (lblSlideID != null && !string.IsNullOrEmpty(lblSlideID.Text))
                {
                    // Delete customer
                    SlideFactory.Delete(Convert.ToInt32(lblSlideID.Text));
                    InintData();

                    // Delete old image
                    var filePath = Request.PhysicalApplicationPath + lblImagePath.Text.Substring(3, lblImagePath.Text.Length - 3);
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                if (GlobalInfo.IsEnableDebugMode) throw;
            }
        }
    }
}